const { Invitation, Resume } = require('../models');
const { Op } = require('sequelize');
const fs = require('fs');
const path = require('path');
const qiniuService = require('../utils/qiniu');
const { validateResume } = require('../utils/validation');

// 获取邀请信息
exports.getInvitationByCode = async (req, res, next) => {
  try {
    const { code } = req.params;
    
    // 查找邀请链接
    const invitation = await Invitation.findOne({
      where: { code }
    });
    
    if (!invitation) {
      return res.status(404).json({
        success: false,
        message: '邀请链接不存在或已过期'
      });
    }
    
    // 检查是否过期
    if (invitation.expiresAt && new Date(invitation.expiresAt) < new Date()) {
      return res.status(400).json({
        success: false,
        message: '邀请链接已过期'
      });
    }
    
    // 检查是否激活
    if (!invitation.isActive) {
      return res.status(400).json({
        success: false,
        message: '邀请链接已停用'
      });
    }
    
    // 检查是否达到最大提交数
    if (invitation.maxSubmissions > 0) {
      const submissionCount = await Resume.count({
        where: { invitation_id: invitation.id }
      });
      
      if (submissionCount >= invitation.maxSubmissions) {
        return res.status(400).json({
          success: false,
          message: '邀请链接已达到最大提交数'
        });
      }
    }
    
    res.json({
      success: true,
      data: {
        id: invitation.id,
        title: invitation.title,
        description: invitation.description,
        position: invitation.position,
        department: invitation.department
      }
    });
  } catch (error) {
    next(error);
  }
};

// 提交简历
exports.submitApplication = async (req, res) => {
  try {
    const {
      linkToken,
      name,
      nickname,
      phone,
      wechat,
      gender,
      age,
      weight,
      education,
      photos,
      hobbies,
      specialSkills,
      canDrink,
      canLivestream,
      acceptNightShift,
      preferredShift,
      weeklyAvailability,
      workExperience,
      gameExperience,
      selfIntroduction
    } = req.body;

    console.log('收到简历提交请求:', {
      linkToken,
      name,
      phone,
      gender,
      photos: photos?.length || 0
    });

    // 验证简历数据
    const validation = validateResume({
      linkToken,
      name,
      phone,
      gender,
      weight,
      photos,
      canDrink,
      canLivestream,
      acceptNightShift,
      preferredShift,
      weeklyAvailability,
      gameExperience
    });

    if (!validation.isValid) {
      console.log('简历验证失败:', validation.errors);
      return res.status(400).json({ 
        success: false,
        message: '表单验证失败',
        errors: validation.errors
      });
    }

    // 查找邀请链接（如果有）
    let invitation = null;
    if (linkToken) {
      invitation = await Invitation.findOne({
        where: { code: linkToken }
      });
    }

    // 处理工作经历数据
    const processedWorkExperience = Array.isArray(workExperience) 
      ? workExperience.filter(exp => 
          exp.company || exp.position || exp.startDate || exp.endDate || exp.reasonForLeaving
        )
      : [];

    // 创建新简历，注意字段名使用下划线命名法
    const resumeData = {
      link_token: linkToken,
      name,
      nickname,
      phone,
      wechat,
      gender,
      age,
      weight,
      education,
      photos,
      hobbies,
      special_skills: specialSkills,
      can_drink: canDrink,
      can_livestream: canLivestream,
      accept_night_shift: acceptNightShift,
      preferred_shift: preferredShift,
      weekly_availability: weeklyAvailability ? JSON.stringify(weeklyAvailability) : null,
      work_experience: processedWorkExperience,
      game_experience: gameExperience,
      self_introduction: selfIntroduction,
      status: 'pending',
      invitation_id: invitation?.id || null
    };

    console.log('准备创建简历:', resumeData);
    
    const resume = await Resume.create(resumeData);

    console.log('简历创建成功:', resume.id);

    res.status(201).json({
      success: true,
      message: '简历提交成功',
      data: {
        id: resume.id,
        name: resume.name,
        createdAt: resume.created_at
      }
    });
  } catch (error) {
    console.error('提交简历失败:', error);
    res.status(500).json({
      success: false,
      message: '提交失败，请稍后重试',
      error: error.message
    });
  }
};

// 获取上传令牌
exports.getUploadToken = async (req, res) => {
  try {
    const { type } = req.query;
    
    if (!type) {
      return res.status(400).json({
        success: false,
        message: '请指定文件类型'
      });
    }
    
    // 生成上传凭证
    const tokenData = qiniuService.generateUploadToken(type);
    
    res.json({
      success: true,
      data: {
        token: tokenData
      }
    });
  } catch (error) {
    console.error('获取上传令牌失败:', error);
    res.status(500).json({
      success: false,
      message: '获取上传令牌失败，请稍后重试',
      error: error.message
    });
  }
};

// 更新简历照片
exports.updateResumePhotos = async (req, res) => {
  try {
    const { resumeId } = req.params;
    const { photos } = req.body;
    
    console.log('更新简历照片:', resumeId, photos?.length || 0);
    
    // 查找简历
    const resume = await Resume.findByPk(resumeId);
    
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }
    console.log('photos', photos);
    // 验证照片数组
    if (!Array.isArray(photos) || photos.length === 0 || photos.length > 5) {

      return res.status(400).json({
        success: false,
        message: '照片数量必须在1-5张之间'
      });
    }
    
    // 验证所有URL是否为七牛云URL
    for (const url of photos) {
      if (!qiniuService.isValidQiniuUrl(url)) {
        return res.status(400).json({
          success: false,
          message: `照片URL格式不正确: ${url}`
        });
      }
    }
    
    // 更新简历的照片URLs
    resume.photos = photos;
    await resume.save();
    
    res.json({
      success: true,
      message: '照片更新成功',
      data: {
        photos: resume.photos
      }
    });
  } catch (error) {
    console.error('更新照片失败:', error);
    res.status(500).json({
      success: false,
      message: '更新照片失败，请稍后重试',
      error: error.message
    });
  }
}; 